﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XiangDongClub.AllProxy;
using XiangDongClub.BLL;
using XiangDongClub.Common;
using XiangDongClub.Model;

namespace XiangDongClub.Activity.Controllers
{
    public class HeShengHuoController : Controller
    {
        

        private readonly ZTManager _ztManager = Proxy.ZTManager;
        private readonly HshManager _hshManager = Proxy.HshManager;
        private readonly AreaManager _areaManager = Proxy.AreaManager;
        private readonly UserManager _userManager = Proxy.UserManager;


        #region 首页

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            List<ZT_RecTicket> ticket = new List<ZT_RecTicket>();
            try
            {
                ticket = _ztManager.GetAllTicke();//领取列表
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("用户进入首页失败，错误信息：{0}", ex.Message));
            }
            ViewBag.Ticket = ticket;
            return View();
        }
        /// <summary>
        /// 获取领取的体验卡
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public JsonResult GetUserRecTicket(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var userRecTicket= _ztManager.GetTicketByPhone(phone);
                return Json(new { Success = true, Code = 0, Message = userRecTicket }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取领取卡券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 单点登录授权
        /// <summary>
        /// 单点登录授权
        /// </summary>
        /// <returns></returns>
        public JsonResult Login(string token)
        {
            Log4NetObject.WriteInfo("请求和生活开始");
            try
            {
                var TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");   //时间戳
                var UID = AESUtils.CreateKey();     //生成一个随机字符串，单点登录不需要这个字段？
                var jsonData = JsonConvert.SerializeObject(new { timeStamp = TimeStamp, token = token, uID = UID });   //JSON 格式data

                //请求和生活单点登录接口
                var msg = "";   //返回的消息
                var jsonResult = "";  //返回的JSON结果      
                if (_hshManager.RequestApi(jsonData, "/v2/loginController/getToken", ref msg, out jsonResult))
                {
                    Log4NetObject.WriteInfo("单点登录成功，返回结果：" + jsonResult);
                    //请求成功，处理结果
                    var jsonObject = JObject.Parse(jsonResult);
                    var Mobile = jsonObject["mobile"].ToString();   //电话
                    //var Mobile = "15002884245";
                    var fuwuId = "";
                    if (_hshManager.HeshenghuoLogin(Mobile, out fuwuId))
                    {
                        CookieHelper.Add("AuthPhone", Mobile);
                        return Json(new { Success = true, Message = "登录成功", phone = Mobile,openid=fuwuId }, JsonRequestBehavior.AllowGet);//成功，返回结果fuwuId
                    }
                    else
                    {
                        return Json(new { Success = false, Message = "登录失败,请稍后再试！" }, JsonRequestBehavior.AllowGet); //失败，返回错误信息
                    }
                }
                else
                {
                    Log4NetObject.WriteError("单点登录失败：" + msg);
                    return Json(new { Success = false, Message = "和生活接口请求失败" + msg }, JsonRequestBehavior.AllowGet); //失败，返回错误信息和空结果  
                }
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("和生活单点登录失败：错误信息：{0}", ex.Message));
                return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }


        /// <summary>
        /// 会员权益查询
        /// </summary>
        /// <param name="fid"></param>
        /// <returns></returns>
        public ActionResult UserDiscount(string phone)
        {
            try
            {
                if(string.IsNullOrEmpty(phone))
                    return Json(new { Success = false, Code = 1, Message = "会员权益查询失败" }, JsonRequestBehavior.AllowGet); //失败  
                var TimeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");   //时间戳
                var UID = AESUtils.CreateKey();     //生成一个随机字符串
                var jsonData = JsonConvert.SerializeObject(new { TimeStamp = TimeStamp, UID = UID, Mobile = phone });   //JSON 格式data
                var msg = "";   //返回的消息
                var jsonResult = "";  //返回的JSON结果     
                if (_hshManager.RequestApi(jsonData, "/UserDiscount/query", ref msg, out jsonResult))
                {
                    Log4NetObject.WriteInfo("会员权益查询，返回结果：" + jsonResult);
                    var jsonObject = JObject.Parse(jsonResult);
                    var status = jsonObject["Status"].ToString();   //会员状态
                    var name = jsonObject["Name"].ToString();   //会员状态
                    if (status != "1" || name !="5")
                        return Redirect("https://hsh.vpclub.cn/activity/myMember/payMoney.html");

                    return Json(new { Success = true, Code = 0, Message = "会员权益查询成功" }, JsonRequestBehavior.AllowGet); //失败  
                }
                return Json(new { Success = false, Code = 1, Message = "会员权益查询失败：" + msg }, JsonRequestBehavior.AllowGet); //失败  

            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}会员权益查询失败，错误信息：{1}", phone, ex.Message));
                return Json(new { Success = false, Code = 3, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion



        #region 免费体验馆
        /// <summary>
        /// 免费体验馆
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public ActionResult FreeShop(int cityId = 1)
        {
            var model = new List<ZT_Shop>();
            var phone = GetUserPhone();
            var areaList = new List<Area>();
            var shopId = 0;
            try
            {
                var ticket = _ztManager.GetTicket(phone, 1).FirstOrDefault();
                if (ticket != null)
                    shopId = ticket.ShopId;

                model = _ztManager.GetShopByParams(cityId, 1);//获取当前场馆
                areaList = _areaManager.GetAllCitys(0);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取免费体验馆失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.TicketShopId = shopId;
            ViewBag.CityList = areaList;
            ViewBag.CityId = cityId;
            return View(model);
        }

        /// <summary>
        /// 领取免费体验券
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public JsonResult RecFreeTicket(string phone, int shopId)
        {
            if (string.IsNullOrWhiteSpace(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var recCount = _ztManager.GetTicket(phone, 1).Count();
                if (recCount >= 1)
                    return Json(new { Success = false, Code = 1, Message = "每人限领一张！" }, JsonRequestBehavior.AllowGet);

                var sur = _ztManager.GetShopTicketSurCount(shopId, 1);
                if (sur <= 0)
                    return Json(new { Success = false, Code = 2, Message = "当前场馆体验券已领完！" }, JsonRequestBehavior.AllowGet);

                ZT_RecTicket ticket = new ZT_RecTicket();
                ticket.Phone = phone;
                ticket.ShopId = shopId;
                ticket.TicketCode = _ztManager.GenerateRandomCode(10);
                ticket.CurType = 1;
                ticket.RecTime = DateTime.Now;
                ticket.State = 1;
                _ztManager.AddTicket(ticket);
                Log4NetObject.WriteInfo(string.Format("{0}用户在和生活领取免费体验券成功，领取场馆：{1}", phone, shopId));
                return Json(new { Success = true, Code = 0, Message = "领取体验券成功！" }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取免费体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        #endregion


        #region 好礼加油站
        /// <summary>
        /// 好礼加油站
        /// </summary>
        /// <returns></returns>
        public ActionResult YearsShop(int cityId = 1)
        {
            var model = new List<ZT_Shop>();
            var phone = GetUserPhone();
            var areaList = new List<Area>();
            var shopId = 0;
            try
            {
                var ticket = _ztManager.GetTicket(phone, 2).FirstOrDefault();//获取当前用户领取的卡券
                if (ticket != null)
                    shopId = ticket.ShopId;
                model = _ztManager.GetShopByParams(cityId, 2);//获取当前场馆
                areaList = _areaManager.GetAllCitys(0);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取好礼加油体验馆失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.TicketShopId = shopId;
            ViewBag.CityList = areaList;
            ViewBag.CityId = cityId;
            return View(model);
        }

        public JsonResult GetShopListMethod(int cityId, int pageType)
        {
            var model = new List<ZT_Shop>();
            try
            {
                model = _ztManager.GetShopByParams(cityId, pageType);//获取当前场馆
                return Json(new { Success = true, CityId = cityId, Message = model }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("用户根据城市获取体验馆失败，场馆类型：{2}，城市：{0}，错误信息：{1}", cityId, ex.Message, pageType));
            }
            return Json(new { Success = false, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

        }


        /// <summary>
        /// 领取好礼加油体验券
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public JsonResult RecYearTicket(string phone, int shopId)
        {
            if (string.IsNullOrEmpty(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var recCount = _ztManager.GetTicket(phone, 2).Count();
                if (recCount >= 1)
                    return Json(new { Success = false, Code = 1, Message = "每人限领一张！" }, JsonRequestBehavior.AllowGet);

                var sur = _ztManager.GetShopTicketSurCount(shopId, 2);
                if (sur <= 0)
                    return Json(new { Success = false, Code = 2, Message = "当前场馆体验券已领完！" }, JsonRequestBehavior.AllowGet);

                int isorder = _ztManager.GetOrderShipCount(phone);//查询用户是否订购
                //if (isorder <= 0)
                //{
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报开始时间：{0}", DateTime.Now));
                //    var password = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_password");            //密码    为预定字符串
                //    var username = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_username");                  //用户名   区分不同用户标识(获取方式需要向手机报申请)
                //    var businessId = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_businessId");               //业务ID  获取对应的业务id  
                //    _ztManager.SyncSjbUserAct(password, username, int.Parse(businessId), phone); //手机报用户订购关系同步
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报结束时间：{0}", DateTime.Now));
                //    isorder = _ztManager.GetOrderShipCount(phone);//同步后再次查询用户是否订购
                //}
                if (isorder <= 0)
                    return Json(new { Success = false, Code = 3, Message = "请您先进行业务订购，方可领取！" }, JsonRequestBehavior.AllowGet);

                ZT_RecTicket ticket = new ZT_RecTicket();
                ticket.Phone = phone;
                ticket.ShopId = shopId;
                ticket.TicketCode = _ztManager.GenerateRandomCode(10);
                ticket.CurType = 2;
                ticket.RecTime = DateTime.Now;
                ticket.State = 1;
                _ztManager.AddTicket(ticket);
                Log4NetObject.WriteInfo(string.Format("{0}用户在和生活领取好礼加油体验券成功，领取场馆：{1}", phone, shopId));
                return Json(new { Success = true, Code = 0, Message = "领取体验券成功！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取好礼加油体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }


        #endregion


        #region 豪礼助力体验券

        /// <summary>
        /// 豪礼助力站
        /// </summary>
        /// <returns></returns>
        public ActionResult CurrentShop(int cityId = 1)
        {
            var model = new List<ZT_Shop>();
            var phone = GetUserPhone();
            var areaList = new List<Area>();
            try
            {
                var ticket = _ztManager.GetTicket(phone, 3).FirstOrDefault();
                if (ticket != null)
                    return Redirect("/HeShengHuo/CurrentUser?shopId=" + ticket.ShopId);

                model = _ztManager.GetShopByParams(cityId, 3);//获取当前场馆
                areaList = _areaManager.GetAllCitys(0);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取豪礼助力体验馆失败，错误信息：{1}", phone, ex.Message));
            }
            ViewBag.CityList = areaList;
            ViewBag.CityId = cityId;
            return View(model);
        }
        /// <summary>
        /// 领取豪礼助力体验券
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public JsonResult RecCurTicket(string phone, int shopId)
        {
            if (string.IsNullOrEmpty(phone))
                return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);

            try
            {
                var recCount = _ztManager.GetTicket(phone, 3).Count();
                if (recCount >= 1)
                    return Json(new { Success = true, Code = 1, Message = shopId }, JsonRequestBehavior.AllowGet);

                var sur = _ztManager.GetShopTicketSurCount(shopId, 3);
                if (sur <= 0)
                    return Json(new { Success = false, Code = 2, Message = "当前场馆体验券已领完！" }, JsonRequestBehavior.AllowGet);

                int isorder = _ztManager.GetOrderShipCount(phone);//查询用户是否订购
                //if (isorder <= 0)
                //{
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报开始时间：{0}", DateTime.Now));
                //    var password = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_password");            //密码    为预定字符串
                //    var username = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_username");                  //用户名   区分不同用户标识(获取方式需要向手机报申请)
                //    var businessId = System.Configuration.ConfigurationManager.AppSettings.Get("shoujibao_businessId");               //业务ID  获取对应的业务id  
                //    _ztManager.SyncSjbUserAct(password, username, int.Parse(businessId), phone); //手机报用户订购关系同步
                //    Log4NetObject.WriteInfo(string.Format("查询用户是否订购手机报结束时间：{0}", DateTime.Now));
                //    isorder = _ztManager.GetOrderShipCount(phone);//同步后再次查询用户是否订购
                //}
                if (isorder <= 0)
                    return Json(new { Success = false, Code = 3, Message = "请您先进行业务订购，方可领取！" }, JsonRequestBehavior.AllowGet);


                ZT_RecTicket ticket = new ZT_RecTicket();
                ticket.Phone = phone;
                ticket.ShopId = shopId;
                ticket.TicketCode = _ztManager.GenerateRandomCode(10);
                ticket.CurType = 3;
                ticket.RecTime = DateTime.Now;
                ticket.State = 0;
                _ztManager.AddTicket(ticket);
                Log4NetObject.WriteInfo(string.Format("{0}用户在和生活领取豪礼加油体验券成功，领取场馆：{1}", phone, shopId));
                return Json(new { Success = true, Code = 0, Message = shopId }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取好礼加油体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 豪礼用户助力
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public ActionResult CurrentUser(int shopId)
        {
            var model = new ZT_Shop();
            var phone = GetUserPhone();
            var helpcount = 0;
            try
            {
                model = _ztManager.GetShopDetailsByShopId(shopId, 3);
                helpcount = _ztManager.GetFriendsHelpByPhone(phone).Count();
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户获取豪礼助力个人页面失败，错误信息：{1}", phone, ex.Message));
            }

            ViewBag.SignPhone = Framework.Utilities.EncryptDES(phone);
            ViewBag.HelpCount = helpcount;
            return View(model);
        }

        public JsonResult RecCurrentTicket(string phone)
        {
            try
            {
                var ticket = _ztManager.GetTicket(phone, 3).FirstOrDefault();
                if (ticket == null)
                    return Json(new { Success = false, Code = 0, Message = "系统错误，请稍后再试！" }, JsonRequestBehavior.AllowGet);
                if (ticket.State == 1)
                    return Json(new { Success = false, Code = 1, Message = "请勿重复领取！" }, JsonRequestBehavior.AllowGet);

                ticket.State = 1;
                ticket.RecTime = DateTime.Now;
                _ztManager.UpdateTicket(ticket);
                return Json(new { Success = true, Code = 0, Message = "领取成功！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户领取豪礼助力体验券失败，错误信息：{1}", phone, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 豪礼助力分享页面
        /// </summary>
        /// <param name="p"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public ActionResult CurrentShare(string p, string openid = "")
        {
            var authURL = System.Configuration.ConfigurationManager.AppSettings["WechatAuthUrl"].ToString();
            if (string.IsNullOrEmpty(openid))
                return Redirect(authURL + "?back=" + Request.Url.AbsoluteUri);

            var model = new ZT_Shop();
            var helpcount = 0;
            try
            {
                var ua = _userManager.GetUnionAccountByFid(p);
                if (ua != null)
                {
                    var ticket = _ztManager.GetTicket(ua.BindPhone, 3).FirstOrDefault();
                    model = _ztManager.GetShopDetailsByShopId(ticket.ShopId, 3);
                    helpcount = _ztManager.GetFriendsHelpByPhone(ua.BindPhone).Count();
                }
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户帮助{1}获取豪礼体验分享页面失败，错误信息：{1}", openid, p, ex.Message));
            }
            ViewBag.HelpCount = helpcount;
            return View(model);
        }

        /// <summary>
        /// 好友助力
        /// </summary>
        /// <param name="p"></param>
        /// <param name="openId"></param>
        /// <returns></returns>
        public JsonResult FightingMethod(string p, string openId)
        {
            //var phone = "";
            try
            {
                var ua = _userManager.GetUnionAccountByFid(p);
                if (ua==null)
                    return Json(new { Success = false, Code = 1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
                var fcount = _ztManager.GetFriendsHelpByPhone(ua.BindPhone).Count();//总人数
                if (fcount >= 30)
                    return Json(new { Success = false, Code = 2, Message = "好友已完成助力，谢谢参与！" }, JsonRequestBehavior.AllowGet);
                var ucount = _ztManager.GetFriendHelpByOpenid(openId).Count();//获取当前用户是否加油
                if (ucount > 0)
                    return Json(new { Success = false, Code = 3, Message = "每个用户只能为好友加油一次！" }, JsonRequestBehavior.AllowGet);

                ZT_FriendsHelp fh = new ZT_FriendsHelp();
                fh.OpenId = openId;
                fh.Phone = ua.BindPhone;
                fh.CreateTime = DateTime.Now;
                var help = _ztManager.AddFriendsHelp(fh);
                if (help == null)
                    return Json(new { Success = false, Code = 4, Message = "为好友加油失败，请稍后再试！" }, JsonRequestBehavior.AllowGet);
             
                return Json(new { Success = true, Code = 0, Message = "为好友加油成功！" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Log4NetObject.WriteError(string.Format("{0}用户为{1}助力失败，错误信息：{2}", openId, p, ex.Message));
            }
            return Json(new { Success = false, Code = -1, Message = "系统繁忙，请稍后再试！" }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        /// <summary>
        /// 成功页面
        /// </summary>
        /// <returns></returns>
        public ActionResult RecTicketSuccess()
        {
            return View();
        }

        public string GetUserPhone()
        {
            return CookieHelper.GetCookie("AuthPhone");
        }
    }
}